package com.zjk.service;

import antlr.StringUtils;
import com.zjk.dao.TagRepository;
import com.zjk.domain.Tag;
import com.zjk.exception.NotFoundException;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @author zhujinkai
 */
@Service
public class TagServiceImpl implements TagService{

    @Autowired
    private TagRepository tagRepository;

    @Override
    public Tag saveTag(Tag type) {
        return tagRepository.save(type);
    }

    @Override
    public Tag getTag(Long id) {
        return tagRepository.getOne(id);
    }

    @Override
    public Tag getTagByName(String name) {
        return tagRepository.findByName(name);
    }

    @Override
    public Tag updateTag(Tag type) {
        Tag t = tagRepository.getOne(type.getId());
        if ( t == null ){
            throw new NotFoundException("不存在该类型");
        }
        BeanUtils.copyProperties(type, t);
        return tagRepository.save(t);
    }

    @Override
    public void deleteTag(Long id) {
        Tag t = tagRepository.getOne(id);
        if ( t == null ) {
            throw new NotFoundException("不存在该类型");
        }else {
            tagRepository.deleteById(id);
        }
    }

    @Override
    public Page<Tag> listTag(Pageable pageable) {
        return tagRepository.findAll(pageable);
    }

    @Override
    public List<Tag> listTag() {
        return tagRepository.findAll();
    }

    @Override
    public List<Tag> listTag(String tagIds) {
        return tagRepository.findAllById(convertToList(tagIds));
    }

    @Override
    public List<Tag> listTagTop(Integer size) {
        Pageable pageable = PageRequest.of(0, size, Sort.by(Sort.Direction.DESC, "blogs.size"));
        return tagRepository.findTopBy(pageable);
    }

    /*将字符串转换为数组*/
    private List<Long> convertToList(String ids){
        List<Long> list = new ArrayList<>();
        if (!"".equals(ids) && ids != null) {
            String[] idArr = ids.split(",");
            for (String id : idArr) {
                list.add(Long.parseLong(id));
            }
        }
        return list;
    }


}
